package com.tamtamy.jtta.utility;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class XMLUtility {

	public static String getNodeValue(String XML, String nodeName){
		String tokenValue = null;
		int start = XML.indexOf("<"+nodeName+">") + ("<"+nodeName+">").length();
		int stop = XML.indexOf("</"+nodeName+">");
		if(start>stop || stop<0) return "";
		try{
		  tokenValue = XML.substring(start, stop);
		}catch (Exception ex){
		  ex.printStackTrace();	
		}		
		return tokenValue;
	}
	
	public static ArrayList<String> getStringList(Document xmlDocument, String listName, String fieldName) {
		ArrayList<String> stringList = new ArrayList<String>();
		Element listElement = (Element) xmlDocument.getElementsByTagName(listName).item(0);
		if (listElement!=null){
			NodeList nodeList = listElement.getElementsByTagName(fieldName);
			if (nodeList != null && nodeList.getLength()>0){
				for (int i = 0; i < nodeList.getLength(); i++) {
					Node node = nodeList.item(i);
					stringList.add(node.getTextContent());
				}
			}
		}
		return stringList;
	}

	public static long getLong(Document xmlDocument, String field){
		return Long.parseLong(getString(xmlDocument, field));		
	}
	
	public static int getInt(Document xmlDocument, String field){
		return Integer.parseInt(getString(xmlDocument, field));		
	}
	
	public static String getString(Document xmlDocument, String field){
		if ((xmlDocument.getElementsByTagName(field)!=null) && (xmlDocument.getElementsByTagName(field).item(0)!=null)){
			return xmlDocument.getElementsByTagName(field).item(0).getTextContent();
		}
		else {
			return null;
		}
		
	}
	
	public static Date getDate(Document xmlDocument, String field){
		Date aDate = null;
		if ((xmlDocument.getElementsByTagName(field)!=null) && (xmlDocument.getElementsByTagName(field).item(0)!=null)){
			try {
				SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
				aDate = dateFormatter.parse( xmlDocument.getElementsByTagName(field).item(0).getTextContent());
			} catch (ParseException e) {
			}
		}
		return aDate;
	}	
	
}
